package com.nx.adaper.shopify.rest;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.google.gson.Gson;
import com.nx.adaper.shopify.model.WebhookDataDto;
import com.nx.adaper.shopify.support.AliMqProps;
import com.nx.biz.shopify.api.dto.ShopifyOrderBizDto;
import com.nx.biz.shopify.api.dto.ShopifyOrderVoItem;
import com.nx.biz.shopify.api.qry.OrderSyncListQry;
import com.nx.biz.shopify.sdk.ShopifySdk.model.constant.TopicConstants;
import com.nx.biz.shopify.service.ShopifyBizService;
import com.nx.common.exception.BusinessException;
import com.nx.common.result.R;
import com.nx.common.tools.CheckTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.message.MessageBuilder;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * shopify对接rest接口
 */
@Slf4j
@RestController
@RequestMapping("/shopify")
public class ShopifyController {

    private static final Gson GSON = new Gson();

    @Resource
    private Producer producer;
    @Resource
    private AliMqProps aliMqProps;

    @Resource
    private ShopifyBizService shopifyBizService;

    /**
     * 查询订单信息
     */
    @PostMapping("/queryOrderBizInfo")
    public R<ShopifyOrderBizDto> queryOrderBizInfo(@RequestBody Map<String, Object> paramsMap) {
        // 订单 => 运单 => 运踪
        String sOrderId = MapUtil.getStr(paramsMap, "sOrderId");
        if (CheckTools.isNullOrEmpty(sOrderId)) {
            throw new BusinessException("订单id为空");
        }
        ShopifyOrderBizDto shopifyOrderBizDto = shopifyBizService.queryOrderBizInfo(sOrderId);
        return R.success("获取成功", shopifyOrderBizDto);
    }

    /**
     * 查询订单同步列表
     */
    @GetMapping("/queryOrderSyncList")
    public R<List<ShopifyOrderVoItem>> queryOrderSyncList(OrderSyncListQry syncListQry) {
        // 转发service查询
        List<ShopifyOrderVoItem> shopifyOrderVoItems = shopifyBizService.queryOrderSyncList(syncListQry);
        return R.success("获取成功", shopifyOrderVoItems);
    }

    /**
     * ------------------------------------------- webhook 回调 ------------------------------------------------
     */

    @PostMapping("/webhooks")
    public void webhooks(@RequestHeader Map<String, String> headers, @RequestBody Object payload) throws Exception {
        log.info("");
        log.info("");
        log.info("----------------------------------------------------- shopify-webhook-[start] -----------------------------------------------------");
        log.info("-> headers:{}", GSON.toJson(Collections.singletonList(headers)));
        log.info("-> payload:{}", GSON.toJson(payload));
        String topic = headers.get("x-shopify-topic");
        String shopDomain = headers.get("x-shopify-shop-domain");
        String requestUUID = IdUtil.simpleUUID();
        log.info("-> shopDomain:{}，topic: {}，进入处理环节，本次请求id：{}", shopDomain, topic, requestUUID);

        WebhookDataDto webhookDataDto = new WebhookDataDto();
        webhookDataDto.setTopic(topic);
        webhookDataDto.setShopDomain(shopDomain);
        webhookDataDto.setPayloadJson(GSON.toJson(payload));

        ClientServiceProvider provider = ClientServiceProvider.loadService();
        MessageBuilder messageBuilder = provider.newMessageBuilder()
                .setTopic(aliMqProps.getTopic())
                //设置消息索引键，可根据关键字精确查找某条消息。
                .setKeys(requestUUID)
                // 将数据设置到body中
                .setBody(GSON.toJson(webhookDataDto).getBytes());

        Message message = null;
        if (topic.equals(TopicConstants.fulfillmentCreate)) {
            message = messageBuilder.setTag(TopicConstants.fulfillmentCreate).build();
        } else if (topic.equals(TopicConstants.orderCreate)) {
            message = messageBuilder.setTag(TopicConstants.orderCreate).build();
        } else if (topic.equals(TopicConstants.orderUpdate)) {
            message = messageBuilder.setTag(TopicConstants.orderUpdate).build();
        } else if (topic.equals(TopicConstants.orderDelete)) {
            message = messageBuilder.setTag(TopicConstants.orderDelete).build();
        } else if (topic.equals(TopicConstants.orderPaid)) {
            message = messageBuilder.setTag(TopicConstants.orderPaid).build();
        } else if (topic.equals(TopicConstants.orderFulfilled)) {
            message = messageBuilder.setTag(TopicConstants.orderFulfilled).build();
        } else if (topic.equals(TopicConstants.fulfillmentRequestCreate)) {
            // todo 这个逻辑上也是不需要的
            message = messageBuilder.setTag(TopicConstants.fulfillmentRequestCreate).build();
        } else {
            log.error("未知的topic {}, payload: {}，无需处理", topic, payload);
        }

        if (CheckTools.isNotNullOrEmpty(message)) {
            log.info("-> topic: {}，已转为mq消息：{}", topic, message);
            try {
                //发送消息，需要关注发送结果，并捕获失败等异常。
                SendReceipt sendReceipt = producer.send(message);
                log.info("-> 消息发送成功，消息id：{}", sendReceipt.getMessageId());
            } catch (Exception e) {
                log.info("-> 消息发送失败，异常堆栈：", e);
            }
        } else {
            log.error("shopify-topic转为mq-message为空，无需发送到消息队列");
        }

        log.info("<- shopDomain:{}，topic: {}，处理完成，本次请求id：{}", shopDomain, topic, requestUUID);
        log.info("----------------------------------------------------- shopify-webhook-[end] -----------------------------------------------------");
    }

}
